use std::fs;

#[derive(Debug)]
pub struct ProcInfo {
    pub pid: i32,
    pub ppid: i32,
    pub name: String,
}

pub fn get_pids() -> Option<Vec<i32>> {
    let mut ret = vec![];
    for entry in fs::read_dir("/proc").ok()? {
        let entry = entry.ok()?;
        let path = entry.path();
        if path.is_dir() {
            let name = path.file_name()?;
            let str = name.to_str()?;
            if let Ok(pid) = str.parse::<i32>() {
                ret.push(pid);
            }
        }
    }
    Some(ret)
}

pub fn get_process_info_with_pid(pid: i32) -> Option<ProcInfo> {
    let info = fs::read_to_string(format!("/proc/{}/status", pid)).ok()?;
    let lines: Vec<(&str, &str)> = info
        .split('\n')
        .map(|s: &str| s.split_once(':'))
        .flatten()
        .collect();

    let mut name = String::new();
    let mut pid = -1;
    let mut ppid = -1;
    for (k, v) in lines {
        match k.trim() {
            "Name" => {
                name = v.trim().into();
            }
            "Pid" => {
                pid = v.trim().parse().unwrap();
            }
            "PPid" => {
                ppid = v.trim().parse().unwrap();
            }
            _ => {}
        }
    }
    Some(ProcInfo { pid, ppid, name })
}
